package com.yb.framework.security.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.alibaba.fastjson.JSON;
import com.yb.framework.core.utils.SecurityUtil;

@Component
public class CustomFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		/**
		 * TopJUI对JSON文件请求方式是POST
		 * SpringBoot框架对静态资源请求，不支持POST请求方式，会报错。
		 * 参考：https://blog.csdn.net/weixin_42074868/article/details/85001093
		 * 
		 * 拦截静态资源请求（JSON文件），重写getMethod()，将请求方式由POST改成GET。
		 * 参考：https://blog.csdn.net/qq_41879343/article/details/105171910
		 */
		if (request.getRequestURI().contains(".json") && !request.getMethod().equals("GET")) {
			request = new HttpMethodRequestWrapper(request, "GET");
			chain.doFilter(request, response);
		}
		
		// 过滤静态资源请求
		if (!(request.getRequestURI().startsWith("/html") || request.getRequestURI().startsWith("/json") || 
				request.getRequestURI().startsWith("/static") || request.getRequestURI().startsWith("/topjui"))) {
			System.out.println();
			System.out.println(">>>>>>>>>> URI : " + request.getRequestURI());
			System.out.println(">>>>>>>>>> username : " + SecurityUtil.getUsername());
			System.out.println(">>>>>>>>>> authoritie : " + JSON.toJSONString(SecurityUtil.getAuthorities()));
		}
		
		chain.doFilter(request, response);
	}
	
	private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
		
		/** 请求方式 **/
		private String method;
		
		public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
			super(request);
			this.method = method;
		}
		
		@Override
		public String getMethod() {
			// TODO Auto-generated method stub
			return method;
		}
	}
}
